#include "rpcserver.h"
#include "os_socket.h"

RPCServer::RPCServer()
{
	m_pThread = NULL;
	m_port = 30001;
	m_pMutex = NULL;
}

RPCServer::~RPCServer()
{

}

int RPCServer::startThread()
{
	os_mutex_create(&m_pMutex);
	if (os_thread_create(RPCServer::ThreadProc, this, &m_pThread) == -1) {
		return -1;
	}
	return 0;
}

int RPCServer::ThreadProc(void *pinstance)
{
	if (!pinstance){
		printf("errorsssss\n");
		return -1;
	}

	RPCServer *server = (RPCServer *)pinstance;
	return server->run();
}

int RPCServer::run()
{
	os_socket_init();

	int sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == INVALID_SOCKET) {
		printf("socket error\n");
		return -1;
	}

	sockaddr_in localAddr = {0};
	localAddr.sin_family = AF_INET;
	localAddr.sin_port = htons(m_port);
	localAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

	if (bind(sock, (sockaddr *)&localAddr, sizeof(localAddr)) != 0) {
		printf("bind error\n");
		return -1;
	}

	listen(sock, 20);

	printf("server started\n");

	while (true)
	{
		int client_sock = 0;
		sockaddr_in client_addr = {0};
		int sLen = sizeof(client_addr);
		client_sock = accept(sock, (sockaddr *)&client_addr, &sLen);

		RPCClient *new_client = new RPCClient();
		new_client->set_sock(client_sock);
		if (!new_client->startThread())
		{
		}
	}

	return 0;
}

void RPCServer::addClient(int sock, RPCClient *client)
{
	os_mutex_lock(m_pMutex);
	m_clientMap[sock] = client;
	os_mutex_unlock(m_pMutex);
}

